package com.person.leetcode.editor.cn;

/**
 * 21.合并两个有序链表
 * 2022-03-31 17:30:49
 **/
public class Sequence_0021_MergeTwoSortedLists {
    public static void main(String[] args) {
        Solution solution = new Sequence_0021_MergeTwoSortedLists().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode() {}
     * ListNode(int val) { this.val = val; }
     * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */

    class Solution {
        public ListNode next(ListNode list1, ListNode list2) {
            int val1 = list1 == null ? 0 : list1.val;
            int val2 = list2 == null ? 0 : list2.val;
            ListNode next1 = list1 == null ? null : list1.next;
            ListNode next2 = list2 == null ? null : list2.next;
            ListNode resNode;

            if (list1 == null && list2 == null) {
                resNode = null;
            } else if (next1 == null && next2 == null) {
                if (val1 > val2) {
                    resNode = list2 == null ? list1 : new ListNode(val2, list1);
                } else {
                    resNode = list1 == null ? list2 : new ListNode(val1, list2);
                }
            } else {
                if (val1 > val2) {
                    resNode = list2 == null ? list1 : new ListNode(val2, next(list1, next2));
                } else {
                    resNode = list1 == null ? list2 : new ListNode(val1, next(list2, next1));
                }
            }

            return resNode;
        }

        public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
            ListNode resNode = next(list1, list2);
            return resNode;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
